import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { FaCodeBranch, FaHistory, FaPen, FaFileAlt } from 'react-icons/fa';
import ReactMarkdown from 'react-markdown';

const GitPanel: React.FC<{ projectPath: string }> = ({ projectPath }) => {
  const [branches, setBranches] = useState<string[]>([]);
  const [logs, setLogs] = useState<any[]>([]);
  const [commitMsg, setCommitMsg] = useState('');
  const [generating, setGenerating] = useState(false);
  const [prSummary, setPrSummary] = useState('');

  const fetchData = async () => {
    try {
      const [branchesRes, logsRes] = await Promise.all([
        axios.post('/api/git', { action: 'branch', project_path: projectPath }),
        axios.post('/api/git', { action: 'log', project_path: projectPath })
      ]);
      setBranches(branchesRes.data.branches || []);
      setLogs(logsRes.data.log || []);
    } catch (e) {}
  };

  useEffect(() => { fetchData(); }, []);

  const generateCommitMessage = async () => {
    setGenerating(true);
    try {
      const diffRes = await axios.post('/api/git', { action: 'diff', project_path: projectPath });
      const diff = diffRes.data.diff || '';
      const resp = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          model: 'groq-llama-3.1-8b-instant',
          messages: [{ role: 'user', content: `Generate a concise git commit message for the following diff:\n${diff}` }],
          project_path: projectPath,
        }),
      });
      const reader = resp.body?.getReader();
      let msg = '';
      while (reader) {
        const { done, value } = await reader.read();
        if (done) break;
        const text = new TextDecoder().decode(value);
        const lines = text.split('\n').filter(l => l.startsWith('data: ')).map(l => l.slice(6));
        for (const line of lines) {
          if (line === '[DONE]') break;
          try {
            const { token } = JSON.parse(line);
            msg += token;
          } catch (e) {}
        }
      }
      setCommitMsg(msg.replace(/ERROR:.*/, '').trim());
    } catch (e) {}
    setGenerating(false);
  };

  const generatePRSummary = async () => {
    try {
      const diffRes = await axios.post('/api/git', { action: 'diff', project_path: projectPath });
      const diff = diffRes.data.diff || '';
      const resp = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          model: 'groq-llama-3.3-70b-versatile',
          messages: [{ role: 'user', content: `Review the following diff and provide a PR summary with suggestions:\n${diff}` }],
          project_path: projectPath,
        }),
      });
      const reader = resp.body?.getReader();
      let summary = '';
      while (reader) {
        const { done, value } = await reader.read();
        if (done) break;
        const text = new TextDecoder().decode(value);
        const lines = text.split('\n').filter(l => l.startsWith('data: ')).map(l => l.slice(6));
        for (const line of lines) {
          if (line === '[DONE]') break;
          try {
            const { token } = JSON.parse(line);
            summary += token;
          } catch (e) {}
        }
      }
      setPrSummary(summary);
    } catch (e) {}
  };

  const commit = async () => {
    await axios.post('/api/git', { action: 'commit', project_path: projectPath, args: { message: commitMsg } });
    fetchData();
    setCommitMsg('');
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg-primary)', padding: 12, overflowY: 'auto' }}>
      <div style={{ fontWeight: 600, marginBottom: 8 }}><FaCodeBranch /> Git</div>

      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>Branches</div>
        {branches.map(b => (
          <div key={b} style={{ padding: '2px 8px', background: 'var(--bg-tertiary)', borderRadius: 4, marginBottom: 2, fontSize: 13 }}>{b}</div>
        ))}
      </div>

      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>Recent Commits</div>
        {logs.map((log, i) => (
          <div key={i} style={{ borderBottom: '1px solid var(--border)', padding: '4px 0', fontSize: 12 }}>
            <span style={{ color: 'var(--accent)' }}>{log.hash?.substring(0,7)} </span>
            {log.message}
          </div>
        ))}
      </div>

      <div style={{ marginBottom: 12 }}>
        <textarea
          style={{ width: '100%', height: 40, background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border)', borderRadius: 4, padding: 4, fontSize: 12 }}
          placeholder="Commit message..."
          value={commitMsg}
          onChange={e => setCommitMsg(e.target.value)}
        />
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <button onClick={generateCommitMessage} disabled={generating} style={{ background: 'var(--accent)', color: 'white', padding: '4px 8px', borderRadius: 4, fontSize: 12, display: 'flex', alignItems: 'center', gap: 4 }}>
            <FaPen /> {generating ? '...' : 'AI Message'}
          </button>
          <button onClick={commit} style={{ background: 'var(--success)', color: 'white', padding: '4px 8px', borderRadius: 4, fontSize: 12 }}>Commit</button>
        </div>
      </div>

      <div style={{ marginBottom: 12 }}>
        <button onClick={generatePRSummary} style={{ background: 'var(--accent)', color: 'white', padding: '4px 12px', borderRadius: 4, fontSize: 12, display: 'flex', alignItems: 'center', gap: 4 }}>
          <FaFileAlt /> Generate PR Summary
        </button>
        {prSummary && (
          <div style={{ marginTop: 8, padding: 8, background: 'var(--bg-secondary)', borderRadius: 4 }}>
            <ReactMarkdown>{prSummary}</ReactMarkdown>
          </div>
        )}
      </div>
    </div>
  );
};

export default GitPanel;