
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Plus, Trash2 } from 'lucide-react';
import TableStylePanel from './TableStylePanel';
import TableElement from './TableElement';
import { createEmptyTable, addTableRow, removeTableRow, addTableColumn, removeTableColumn, updateTableCell } from '@/lib/tableUtils';
import { ScrollArea } from '@/components/ui/scroll-area';

const TableElementDialog = ({ 
  open, 
  onOpenChange, 
  initialData, 
  initialStyles, 
  onSave 
}) => {
  const [tableData, setTableData] = useState([]);
  const [styles, setStyles] = useState({});
  const [activeTab, setActiveTab] = useState('structure');

  useEffect(() => {
    if (open) {
      setTableData(initialData || createEmptyTable(3, 3));
      setStyles(initialStyles || {
        borderColor: '#e2e8f0',
        cellBgColor: '#ffffff',
        headerBgColor: '#f8fafc',
        borderWidth: 1,
        borderStyle: 'solid',
        fontSize: '11',
        textAlign: 'left',
        padding: 8,
        firstRowIsHeader: true
      });
    }
  }, [open, initialData, initialStyles]);

  const handleSave = () => {
    onSave({ content: { data: tableData }, styles });
    onOpenChange(false);
  };

  const handleCellChange = (rowIndex, colIndex, value) => {
    setTableData(prev => updateTableCell(prev, rowIndex, colIndex, value));
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[900px] h-[90vh] flex flex-col p-0 gap-0">
        <DialogHeader className="px-6 py-4 border-b">
          <DialogTitle>Configure Table</DialogTitle>
          <DialogDescription>Structure your table data and customize styling.</DialogDescription>
        </DialogHeader>

        <div className="flex-1 flex overflow-hidden">
          <div className="flex-1 flex flex-col bg-muted/30 overflow-hidden border-r">
            <div className="p-2 border-b bg-card flex justify-between items-center px-4">
               <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                 Dimensions: {tableData.length} Rows × {tableData[0]?.length || 0} Cols
               </span>
               <div className="flex gap-2">
                 <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setTableData(prev => addTableRow(prev))}>
                   <Plus className="w-3 h-3 mr-1" /> Add Row
                 </Button>
                 <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setTableData(prev => addTableColumn(prev))}>
                   <Plus className="w-3 h-3 mr-1" /> Add Col
                 </Button>
               </div>
            </div>

            <ScrollArea className="flex-1 p-6">
                <div className="bg-card shadow rounded-lg p-6 min-w-max">
                  <div className="inline-grid gap-1" style={{ 
                      gridTemplateColumns: `auto ${tableData[0]?.map(() => 'minmax(120px, 1fr)').join(' ')}` 
                  }}>
                      <div className="col-start-1"></div>
                      {tableData[0]?.map((_, colIndex) => (
                          <div key={`head-${colIndex}`} className="flex flex-col items-center justify-end pb-2 gap-1 group">
                              <span className="text-[10px] text-muted-foreground font-mono">Col {colIndex + 1}</span>
                              <Button 
                                variant="ghost" 
                                size="icon" 
                                className="h-5 w-5 rounded-full text-muted-foreground hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity"
                                onClick={() => setTableData(prev => removeTableColumn(prev, colIndex))}
                                title="Delete Column"
                              >
                                  <Trash2 className="w-3 h-3" />
                              </Button>
                          </div>
                      ))}

                      {tableData.map((row, rowIndex) => (
                          <React.Fragment key={`row-${rowIndex}`}>
                              <div className="flex flex-row items-center justify-end pr-2 gap-1 group">
                                  <Button 
                                    variant="ghost" 
                                    size="icon" 
                                    className="h-5 w-5 rounded-full text-muted-foreground hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity"
                                    onClick={() => setTableData(prev => removeTableRow(prev, rowIndex))}
                                    title="Delete Row"
                                  >
                                      <Trash2 className="w-3 h-3" />
                                  </Button>
                                  <span className="text-[10px] text-muted-foreground font-mono">Row {rowIndex + 1}</span>
                              </div>
                              
                              {row.map((cell, colIndex) => (
                                  <div key={`${rowIndex}-${colIndex}`} className="relative">
                                      <Input 
                                          className={`h-9 text-xs focus:ring-1 focus:ring-ring ${
                                              styles.firstRowIsHeader && rowIndex === 0 ? 'bg-muted/50 font-semibold' : 'bg-background'
                                          }`}
                                          value={cell}
                                          onChange={(e) => handleCellChange(rowIndex, colIndex, e.target.value)}
                                          placeholder="..."
                                      />
                                  </div>
                              ))}
                          </React.Fragment>
                      ))}
                  </div>
                </div>
            </ScrollArea>
          </div>

          <div className="w-[300px] flex flex-col bg-card">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full flex-1 flex flex-col">
              <div className="px-4 pt-4 border-b">
                <TabsList className="w-full grid grid-cols-2">
                  <TabsTrigger value="structure">Preview</TabsTrigger>
                  <TabsTrigger value="style">Styling</TabsTrigger>
                </TabsList>
              </div>

              <div className="flex-1 overflow-y-auto p-4">
                <TabsContent value="structure" className="mt-0 h-full">
                    <div className="space-y-4">
                        <div className="rounded border p-1 bg-muted/50 min-h-[200px] flex items-center justify-center">
                            <div className="bg-card p-4 shadow-sm w-full">
                                <TableElement tableData={tableData} styles={styles} />
                            </div>
                        </div>
                        <p className="text-[10px] text-muted-foreground text-center">
                            This is how the table will look in the document.
                        </p>
                    </div>
                </TabsContent>

                <TabsContent value="style" className="mt-0">
                  <TableStylePanel styles={styles} onChange={setStyles} />
                </TabsContent>
              </div>
            </Tabs>
          </div>
        </div>

        <DialogFooter className="px-6 py-4 border-t bg-muted/30">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSave}>Save Configuration</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export { TableElementDialog };
export default TableElementDialog;
